package serial_utils

import (
	"dgo/goutils/utils"
	"errors"
	"fmt"
	"github.com/tarm/serial"
	"io"
	"strings"
	"time"
)

func SerialConfString(this *serial.Config) string {
	var sb utils.BytesBuilder
	sb.Appendf("name:%s, Baud:%d", this.Name, this.Baud)
	if this.ReadTimeout > 0 {
		sb.Appendf(",readTimeout:%s", this.ReadTimeout)
	}
	return sb.String()
}

/*
*

	com:///dev/ttyS1:115200/[TIMEOUT_SECOND]
*/
func CreateSerialRWCFromCommandLine(cmdstr string) (io.ReadWriteCloser, error) {
	ok, cmdstr := utils.CheckTrimPrefix(cmdstr, "com://")
	if !ok {
		return nil, nil
	}

	var baudrate int = 115200
	name := cmdstr
	serialconf := &serial.Config{
		Name: name,
	}
	strs := strings.SplitN(cmdstr, ":", 2)
	if len(strs) > 1 {
		serialconf.Name = strs[0]
		strs = strings.Split(strs[1], "/")
		{ // :115200
			serialconf.Baud = utils.StrToIntDef(strs[0], baudrate)
		}

		if len(strs) > 1 {
			secs := utils.StrToIntDef(strs[1], 0)
			if secs > 0 {
				serialconf.ReadTimeout = time.Second * time.Duration(secs)
			}
		}
	}

	pt, err := serial.OpenPort(serialconf)
	if err != nil {
		return nil, errors.New(fmt.Sprintf("(%s)%s", SerialConfString(serialconf), err.Error()))
	} else {
		return pt, nil
	}
}
